<template>
  <el-row style="width: 100%;">
    <el-col :span="4">
      <el-button type="danger" style="height: 32px;width: 70px; line-height: 32px;" @click="handleBatchDelete()"
      :disabled="isdelete">
        <el-icon>
          <DeleteFilled />
        </el-icon>
        &nbsp;删除
      </el-button>
      <el-button type="primary" style="height: 32px;width: 90px; line-height: 32px;" @click="handleAdd()">
        <el-icon>
          <Plus />
        </el-icon>
        &nbsp;新增用户
      </el-button>
    </el-col>
    <el-col :span="2">
      <el-select v-model="search.role_id" style="width: 100px;height:32px" placeholder="角色">
        <el-option label="管理员" value="1" />
        <el-option label="普通用户" value="2" />
      </el-select>
    </el-col>
    <el-col :span="6">
      <el-input v-model="search.massage" style="width: 240px;height: 32px" placeholder="请输入搜索的内容" />
      <el-button type="primary" style="height: 32px;width: 65px; line-height: 32px;margin-left: 10px;"
        @click="handleSearch()">
        <el-icon>
          <Search />
        </el-icon>
        &nbsp;搜索
      </el-button>
    </el-col>
  </el-row>
  <el-row style="margin-top: 5px">
    <el-col :span="24">
      <el-table ref="multipleTableRef" :data="userData" style="width: 100%">
        <el-table-column type="selection" width="30" />
        <el-table-column label="序号" align="center" prop="index" width="60" />
        <el-table-column label="用户ID" align="center" prop="userid" width="120" />
        <el-table-column label="用户名" align="center" prop="username" width='120' />
        <el-table-column label="密码" align="center" prop="password" width='120' />
        <el-table-column label="姓名" align="center" prop="name" width='100' />
        <el-table-column label="性别" align="center" width="60" #default="scope">
          {{ scope.row.sex === '1' ? '男' : '女' }}
        </el-table-column>
        <el-table-column label="年龄" align="center" width="60" prop="age" />
        <el-table-column label="邮箱" align="center" prop="email" width="240" />
        <el-table-column label="电话" align="center" prop="phone" width="120" />
        <el-table-column label="角色" align="center" prop="role_id">
          <template #default="scope">
            <el-tag v-if="scope.row.role_id === '1'" type="success">管理员</el-tag>
            <el-tag v-else-if="scope.row.role_id === '2'">普通用户</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="按钮" align="center" width="160">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
              <el-icon>
                <Edit />
              </el-icon>
              修改
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
              <el-icon>
                <DeleteFilled />
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background layout="prev, pager, next" :total="total" @current-change="currentChange"
        style="margin-left: 28%; margin-top: 10px " />
    </el-col>
  </el-row>
  <UserDialog :dialogFormVisible :EditUser="edituser" :title="title" @update_dialogFormVisable="(newval) => {
    dialogFormVisible = false;
  }"></UserDialog>
</template>

<script lang="ts" setup>
import UserDialog from './../components/UserDialog.vue'
import { onMounted, ref, watchEffect } from 'vue'
import { ElMessage, ElMessageBox } from "element-plus";
import { deleteuserApi, getUserListApi, searchuserApi } from '@/api/common';
import { ElTable } from 'element-plus'

const search = ref({
  role_id: '',
  massage: '',
})
const handleSearch = () => {
  searchuserApi(search.value).then((res) => {
    if (res.data.code === 200) {
      ElMessage.success("用户数据更新成功！")
    }
  }).catch((err) => {
    ElMessage.error("服务器错误！")
  })
}

interface User {
  index: number
  userid: number
  username: string
  password: string
  name: string
  sex: string
  age: number
  email: string
  phone: string
  role_id: number
}
const title = ref()
const edituser = ref()
var dialogFormVisible = ref(false)
const total = ref(100)
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const currentChange = (val: number) => {
  getUserData(val);
}
const handleEdit = (index: number, row: User) => {
  title.value = "修改用户信息"
  edituser.value = row;
  dialogFormVisible.value = true;
}
const handleAdd = () => {
  title.value = "新增用户信息"
  dialogFormVisible.value = true;
  edituser.value = {
    username: "",
    password: "",
    name: "",
    sex: "1",
    age: null,
    email: "",
    phone: "",
    role_id: '2'
  };
}
const handleDelete = (index: number, row: User) => {
  ElMessageBox.confirm("是否确认删除", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteuserApi({ userid: row.userid }).then(res => {
        if (res.data.code === 200) {
          ElMessage.success("删除成功！")
        }
        if (res.data.code === 500) {
          ElMessage.error("删除失败！")
        }
      }).catch(() => {
        ElMessage.error("删除失败！")
      })
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除!",
      });
    });
}
const getUserList = () => {
  getUserListApi().then(res => {
    tableData.value = res.data.data
    ElMessage.success({ message: '获取用户数据成功！' })
    total.value = res.data.data.length;
    getUserData(1);
  })
}
const getUserData = (cur: number) => {
  userData.value = tableData.value.slice(cur * 10 - 10, cur * 10)
}
onMounted(() => {
  getUserList();
})
const tableData = ref([])
const userData = ref([])


// 添加selectedRows来存储选中的行
const selectedRows = ref();
const isdelete = ref()
// 监听选中行的变化
watchEffect(() => {
  selectedRows.value = multipleTableRef.value?.getSelectionRows().map((row:any) => row.userid);
  console.log(selectedRows.value);
  isdelete.value = (selectedRows.value?.length === 0) ? true : false
});

// 批量删除方法
const handleBatchDelete = async () => {
  const confirmResult = await ElMessageBox.confirm(`确定删除选中的${selectedRows.value.length}项吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  });

  if (confirmResult === 'confirm') {
    try {
      // 假设后端API接受一个userid数组进行批量删除
      const response = await deleteuserApi({ userid: selectedRows.value });
      if (response.data.code === 200) {
        ElMessage.success('批量删除成功！');
        // 删除后可以考虑刷新数据
        await getUserList();
      } else {
        ElMessage.error(response.data.message || '批量删除失败！');
      }
    } catch (err) {
      ElMessage.error('服务器错误！');
    }
  }
}

</script>

<style></style>